package 动态规划;

public class _931_下降路径最小和 {
    public int minFallingPathSum(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
        int[][] dp = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < matrix[0].length; i++) {
            dp[0][i] = matrix[0][i];
        }

        for (int i = 1; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                if (j == 0) {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j + 1]) + matrix[i][j];
                } else if (j == dp[0].length - 1) {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + matrix[i][j];
                } else {
                    dp[i][j] = Math.min(
                            Math.min(dp[i - 1][j - 1], dp[i - 1][j + 1]),
                            dp[i - 1][j])
                            + matrix[i][j];
                }
            }
        }

        int minValue = dp[matrix.length - 1][0];
        for (int i = 1; i < dp[0].length; i++) {
            minValue = Math.min(minValue, dp[matrix.length - 1][i]);
        }

        return minValue;
    }
}
